home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2316 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  75 lines

  1. Path: ix.netcom.com!netnews
  2. From: miker3@ix.netcom.com (Mike Rubenstein)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: When to use "->" vs "." when calling Member functions
  5. Date: Wed, 17 Jan 1996 02:08:39 GMT
  6. Organization: Netcom
  7. Message-ID: <30fc54cc.83447808@nntp.ix.netcom.com>
  8. References: <4dhea1$6v8@ornews.intel.com>
  9. NNTP-Posting-Host: ix-dc7-23.ix.netcom.com
  10. X-NETCOM-Date: Tue Jan 16  6:08:20 PM PST 1996
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. thurman_b_miller@ccm2.hf.intel.com (Thurman Miller) wrote:
  14.  
  15. |>I'm confused, so please no harsh remarks :)
  16. |>
  17. |>If I've got:
  18. |>
  19. |>class Cfoo
  20. |>{
  21. |>    something * getptr();
  22. |>    somethingelse* m_other;
  23. |>}
  24. |>
  25. |>something * foo::getptr()
  26. |>{
  27. |>    return m_other;
  28. |>}
  29. |>
  30. |>
  31. |>Now...if I'm in another class....
  32. |>
  33. |>    Cfoo foo;
  34. |>    somethingelse* = foo.getptr();
  35. |>
  36. |>why doesn't the following work?
  37. |>
  38. |>    somethingelse* = foo->getptr();
  39. |>
  40. |>I get compile error about no "->" overloaded operator....
  41. |>
  42. |>Can someone point out the obvious when I use one notation over
  43. |>another?
  44.  
  45. It's really quite simple.  Let's ignore overloading operator->.  If
  46. foo is a pointer to Cfoo, then you need to use foo->getptr().  If foo
  47. is an instance of Cfoo or a reference to Cfoo, then you must use
  48. foo.getptr().
  49.  
  50. Example:
  51.  
  52.     class A {
  53.       public:
  54.         void f();
  55.     };
  56.  
  57.     A a;        // a is an instance of A
  58.     A* pa = new A;    // pa is a pointer to A
  59.     A& ra = a;    // ra is a reference to A
  60.  
  61.     a.f();
  62.     (&a)->f();    // if a is an instance of A, then &a is a 
  63.             // pointer to A
  64.     pa->f();
  65.     (*pa).f();    // if pa is a pointer to A, *pa is an instance
  66.  
  67.             // of A.  By definition, the previous 
  68.             // statement and this are equivalent
  69.     ra.f();
  70.     (&ra)->f();    // if ra is a reference to A, then &ra is a 
  71.             // pointer to A
  72.  
  73.  
  74. Michael M Rubenstein
  75.